package club.bigtian.sync.controller;

import club.bigtian.sync.model.TestConnectionRequest;
import club.bigtian.sync.model.TestConnectionResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 测试数据库连接控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/config")
public class TestConnectionController {

    /**
     * 测试数据库连接
     * 
     * @param request 测试连接请求
     * @return 测试连接响应
     */
    @PostMapping("/test-connection")
    public TestConnectionResponse testConnection(@RequestBody TestConnectionRequest request) {
        log.info("测试{}数据库连接: {}:{}/{}", 
                request.getType(), 
                request.getHost(), 
                request.getPort(), 
                request.getDatabase());
        
        try {
            if ("mysql".equalsIgnoreCase(request.getType())) {
                return testMySQLConnection(request);
            } else if ("clickhouse".equalsIgnoreCase(request.getType())) {
                return testClickHouseConnection(request);
            } else {
                return TestConnectionResponse.fail("不支持的数据库类型: " + request.getType());
            }
        } catch (Exception e) {
            log.error("测试数据库连接失败", e);
            return TestConnectionResponse.fail(e.getMessage());
        }
    }
    
    /**
     * 测试MySQL连接
     * 
     * @param request 测试连接请求
     * @return 测试连接响应
     */
    private TestConnectionResponse testMySQLConnection(TestConnectionRequest request) {
        String url = String.format("jdbc:mysql://%s:%d/%s?useSSL=false&serverTimezone=UTC", 
                request.getHost(), request.getPort(), request.getDatabase());
        
        try {
            // 加载MySQL驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            
            // 尝试连接
            try (Connection conn = DriverManager.getConnection(url, request.getUsername(), request.getPassword())) {
                if (conn.isValid(5)) {
                    log.info("MySQL连接成功");
                    return TestConnectionResponse.success();
                } else {
                    log.warn("MySQL连接无效");
                    return TestConnectionResponse.fail("连接无效");
                }
            }
        } catch (ClassNotFoundException e) {
            log.error("MySQL驱动未找到", e);
            return TestConnectionResponse.fail("MySQL驱动未找到: " + e.getMessage());
        } catch (SQLException e) {
            log.error("MySQL连接失败", e);
            return TestConnectionResponse.fail("MySQL连接失败: " + e.getMessage());
        }
    }
    
    /**
     * 测试ClickHouse连接
     * 
     * @param request 测试连接请求
     * @return 测试连接响应
     */
    private TestConnectionResponse testClickHouseConnection(TestConnectionRequest request) {
        String url = String.format("jdbc:clickhouse://%s:%d/%s", 
                request.getHost(), request.getPort(), request.getDatabase());
        
        try {
            // 加载ClickHouse驱动
            Class.forName("ru.yandex.clickhouse.ClickHouseDriver");
            
            // 尝试连接
            try (Connection conn = DriverManager.getConnection(url, request.getUsername(), request.getPassword())) {
                if (conn.isValid(5)) {
                    log.info("ClickHouse连接成功");
                    return TestConnectionResponse.success();
                } else {
                    log.warn("ClickHouse连接无效");
                    return TestConnectionResponse.fail("连接无效");
                }
            }
        } catch (ClassNotFoundException e) {
            log.error("ClickHouse驱动未找到", e);
            return TestConnectionResponse.fail("ClickHouse驱动未找到: " + e.getMessage());
        } catch (SQLException e) {
            log.error("ClickHouse连接失败", e);
            return TestConnectionResponse.fail("ClickHouse连接失败: " + e.getMessage());
        }
    }
} 